package com.jn.zhinongbao.adapter.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.adapter.ProductAdapter;
import com.example.supportingagriculturaltreasures.bean.Product;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private RecyclerView recyclerView;
    private ProductAdapter adapter;
    private TabLayout categoryTabs;
    private OnSearchClickListener onSearchClickListener;
    private DatabaseHelper databaseHelper;
    private List<Product> allProducts = new ArrayList<>();

    public interface OnSearchClickListener {
        void onSearchClick();
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof OnSearchClickListener) {
            onSearchClickListener = (OnSearchClickListener) context;
        }
        databaseHelper = new DatabaseHelper(context);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        setupCategoryTabs();
        setupRecyclerView();
        loadProducts();
    }

    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        categoryTabs = view.findViewById(R.id.category_tabs);
    }

    private void setupCategoryTabs() {
        categoryTabs.addTab(categoryTabs.newTab().setText("推荐"));
        categoryTabs.addTab(categoryTabs.newTab().setText("水果蔬菜"));
        categoryTabs.addTab(categoryTabs.newTab().setText("米面粮油"));
        categoryTabs.addTab(categoryTabs.newTab().setText("农资农具"));

        categoryTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 根据选中的tab加载不同的商品数据
                filterProductsByCategory(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    private void setupRecyclerView() {
        // 设置瀑布布局，2列
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        
        adapter = new ProductAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);
    }

    private void loadProducts() {
        // 从数据库加载所有商品
        if (databaseHelper != null) {
            allProducts = databaseHelper.getAllProducts();
            // 默认显示全部商品（推荐）
            adapter.updateProducts(allProducts);
        }
    }

    private void filterProductsByCategory(int tabPosition) {
        List<Product> filteredProducts = new ArrayList<>();
        
        switch (tabPosition) {
            case 0: // 推荐 - 显示全部商品
                filteredProducts = allProducts;
                break;
            case 1: // 水果蔬菜
                for (Product product : allProducts) {
                    if ("水果蔬菜".equals(product.getCategory())) {
                        filteredProducts.add(product);
                    }
                }
                break;
            case 2: // 米面粮油
                for (Product product : allProducts) {
                    if ("米面粮油".equals(product.getCategory())) {
                        filteredProducts.add(product);
                    }
                }
                break;
            case 3: // 农资农具
                for (Product product : allProducts) {
                    if ("农资农具".equals(product.getCategory())) {
                        filteredProducts.add(product);
                    }
                }
                break;
        }
        
        adapter.updateProducts(filteredProducts);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 页面恢复时重新加载数据
        loadProducts();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 